package br.com.centrodata.controller;

import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.centrodata.dao.SituationDao;
import br.com.centrodata.model.Situation;

/**
 *
 * @author João Fernandes Lima Neto
 */
@Resource
public class SituationController implements GenericController<Situation> {

    private Result       result;
    private Validator    validator;
    private SituationDao dao;

    public SituationController(Result result, Validator validator, SituationDao dao) {
        this.result    = result;
        this.validator = validator;
        this.dao       = dao;
    }

    @Path("/situation/index")
    @Get
    @Override
    public void index() {
        result.include("situations", dao.search());
    }

    @Path("/situation/new")
    @Get
    @Override
    public void form() {
    }

    @Path("/situation/{situation.id}")
    @Get
    @Override
    public void form(Situation situation) {
        result.include("situation", dao.search(situation.getId()));
    }

    @Path("/situation/delete/{situation.id}")
    @Get
    @Override
    public void delete(Situation situation) {
        try{
            dao.del(situation);
            result.include("notice", "Registro deletado com sucesso");
        }catch(Exception e){
            result.include("error", "Ocorreu um erro ao tentar deletar o registro");
        }
    }

    @Path("/situation/save")
    @Post
    @Override
    public void save(Situation situation) {
        
        boolean isEdit = situation.getId() > 0;
        
        /* se estiver Editando */
        if(isEdit){
            this.dao.update(situation);
            result.include("notice", "Usuário [" + situation.getDescricao() + "] atualizado com sucesso.");
        }else{
            this.dao.add(situation);
            result.include("notice", "Usuário [" + situation.getDescricao() + "] inserido com sucesso.");
        }
        result.forwardTo(this).index();
    }
    
}
